﻿using System;

namespace Needle.Utils.Extensions
{
    /// <summary>
    /// System.IServicerProvider extension methods
    /// </summary>
    public static class IServiceProviderExtensions
    {
        /// <summary>
        /// Generic implementation of IServiceProvider.GetService(Type serviceType)
        /// </summary>
        public static TService GetService<TService>(this IServiceProvider serviceProvider)
            where TService : class
        {
            if (serviceProvider == null)
                throw new NullReferenceException("IServiceProvider instance is null");
            return (TService)serviceProvider.GetService(typeof(TService));
        }

        /// <summary>
        /// returns true if there is a service of type TService available
        /// </summary>
        public static bool ContainsService<TService>(this IServiceProvider serviceProvider)
            where TService : class
        {
            if (serviceProvider == null)
                throw new NullReferenceException("IServiceProvider instance is null");
            return serviceProvider.GetService(typeof(TService)) != null;
        }

        /// <summary>
        /// returns true if there is a service of type serviceType available
        /// </summary>
        public static bool ContainsService(this IServiceProvider serviceProvider, Type serviceType)
        {
            if (serviceProvider == null)
                throw new NullReferenceException("IServiceProvider instance is null");
            return serviceProvider.GetService(serviceType) != null;
        }
    }
}
